package com.efounder.agency.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.efounder.activity.TabBottomActivity;
import com.efounder.activity.TabBottomActivity.TabBottomActivityResultListener;
import com.efounder.adapter.TaskListViewAdapter;
import com.efounder.agency.utils.TokenHelper;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.model.AgentTaskModel;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AndroidEnvironmentVariable;
import com.efounder.util.CommonPo;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.pansoft.espflow.util.FlowTaskUtil;
import com.pansoft.xmlparse.OptionParser;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;


/**
 * OA,合同，费用报销 待办已办数据的列表
 *
 * @author yqs 2016.8.3
 */
@SuppressLint({"InflateParams", "HandlerLeak"})
public class TaskListDataFragment extends BaseFragment implements
        TabBottomActivityResultListener,
        OnClickListener {
    private static final String TAG = "TaskListDataFragment";

    String titleStr;

    /**
     * 勘探局分公司token
     */
    private String KTJFGSId = null;

    /** 内蒙分公司token */
    // private String NMYTFGSId = null;

    /**
     * 普光气田分公司分公司token
     */
    private String PGYTFGSId = null;

    /**
     * 中原油田分公司token
     */
    private String ZYYTFGSId = null;

    /**
     * 中原油田机关token
     */
    private String ZYYTJGId = null;

    /**
     * 合同管理token
     */
    private String CONTRACTId = null;

    private String ZYYTJG = "ZYYTJG";// 油田机关OA
    private String KTJFGS = "KTJFGS";// 勘探局OA
    // private String NMYTFGS = "NMYTFGS";// 内蒙分公司OA
    private String PGYTFGS = "PGYTFGS";// 普光OA
    private String ZYYTFGS = "ZYYTFGS";// 油田分公司OA
    private String CONTRACT = "CONTRACT";// 合同审批
    private String FFS = "FFS";// 费用报销
    private String GKOA = "GKOA";// 国勘OA
    private String GKZBOA = "GKZBOA";// 国勘总部OA
    private Map<String, String> map = new LinkedHashMap<String, String>();
    private List<EFRowSet> listData;
    private AgentTaskModel model;
    private TaskListViewAdapter listViewAdapter;
    private LoadDataAsyncTask loadDataAsyncTask;

    private String typeString;// 代办或者已办
    private int startNum = 0;
    private int endNum = 10;
    private int contractNum = 1;// 合同请求数据从1开始
    private int gongwenNum = 0;// 公文审批请求数据从0开始

    private boolean hasLoadData = false;
    RelativeLayout include;
    // LinearLayout linearLayout;
    LinearLayout searchLyaout;
    EditText searchEditText;
    Button searchButton;
    private ListView pullToRefreshListView;
    private SmartRefreshLayout mSrl;

    public TaskListDataFragment(String str) {
        super();
        this.titleStr = str;
    }

    public TaskListDataFragment(String string, Object id) {
        super();
        this.typeString = id.toString();
        System.out.println("任务类型：" + typeString);
    }

    public TaskListDataFragment() {
        super();

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof TabBottomActivity) {
            TabBottomActivity tabBottomActivity = (TabBottomActivity) activity;
            tabBottomActivity.setOnTabBottomActivityResultListener(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // if (isAlone() && !hasLoadData) {
        // new TokenLoadAsyncTask().execute();
        // }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "onStop");
        if (loadDataAsyncTask != null) {
            loadDataAsyncTask.cancel(true);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        model = (AgentTaskModel) getActivity().getIntent()
                .getSerializableExtra("model");

        if (model == null) {
            model = (AgentTaskModel) this.getArguments().getSerializable("model");
        }

        // allMap = new HashMap<String, List<EFRowSet>>();
        listData = new ArrayList<EFRowSet>();
        // loadDataAsyncTask = new LoadDataAsyncTask();

        map.put(ZYYTJG, "中原油田机关公文审批");
        map.put(KTJFGS, "中原油田勘探局公文审批");
        // map.put(NMYTFGS, "中原油田内蒙探区公文审批");
        map.put(PGYTFGS, "普光分公司公文审批");
        map.put(ZYYTFGS, "中原油田分公司公文审批");
        map.put(GKOA, "国勘OA");
        map.put(GKZBOA, "国勘总部OA");
        if (!"dy".equals(typeString) && !"yy".equals(typeString)) {
            map.put(CONTRACT, "合同管理");
        }

        View root = inflater.inflate(R.layout.fg_new_agent_second, null);
        searchLyaout = (LinearLayout) root
                .findViewById(R.id.agent_search_layout);

        if ("yb".equals(typeString) || "yy".equals(typeString)) {
            searchLyaout.setVisibility(View.VISIBLE);
        }
        // 如果是待办 待阅 或者是合同管理,费用报销时，隐藏搜索框
        if (model.getType().equals(CONTRACT) || model.getType().equals(FFS)) {
            searchLyaout.setVisibility(View.GONE);
        }
        searchEditText = (EditText) root.findViewById(R.id.et_search);
        searchButton = (Button) root.findViewById(R.id.searchbut);
        searchButton.setOnClickListener(this);

        pullToRefreshListView = (ListView) root.findViewById(R.id.pullToRefreshListView);
        mSrl = (SmartRefreshLayout) root.findViewById(R.id.srl);
        mSrl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                // 上拉加载更多

                startNum = endNum + 1;
                endNum = endNum + 10;
                contractNum = contractNum + 10;
                gongwenNum = gongwenNum + 10;

                if (loadDataAsyncTask != null) {
                    loadDataAsyncTask.cancel(true);

                }
                loadDataAsyncTask = new LoadDataAsyncTask();
                loadDataAsyncTask
                        .executeOnExecutor(Executors.newCachedThreadPool());
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                // 下拉刷新
                startNum = 0;
                endNum = 10;
                contractNum = 1;
                gongwenNum = 0;
                listData.clear();
                listViewAdapter.notifyDataSetChanged();

                if (loadDataAsyncTask != null) {
                    loadDataAsyncTask.cancel(true);

                }
                loadDataAsyncTask = new LoadDataAsyncTask();
                loadDataAsyncTask
                        .executeOnExecutor(Executors.newCachedThreadPool());
            }
        });
        // listview加在数据
        listViewAdapter = new TaskListViewAdapter(getActivity(), listData);
        pullToRefreshListView.setAdapter(listViewAdapter);
        pullToRefreshListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                EFRowSet child = (EFRowSet) listViewAdapter
                        .getItem(position - 1);
                if (child.getString("canopen", "").equals("0")) {
                    ToastUtil.showToast(getActivity(), "不支持查阅的文件类型");
                    return;
                }

                Bundle bundle = new Bundle();
                bundle.putSerializable("data", child);
                bundle.putSerializable("system", model.getType());
                bundle.putSerializable("type", typeString);

                Intent intent = new Intent(getActivity(),
                        TaskDetailDynamicActivity.class);
                // VideoTreeListActivity.class);
                intent.putExtra("dataSource", bundle);
                getActivity().startActivity(intent);

            }
        });

        include = (RelativeLayout) root.findViewById(R.id.include);
        // 判断fragment是否是单独的
        if (isAlone()) {
            include.setVisibility(View.VISIBLE);
        } else {
            include.setVisibility(View.GONE);
        }
        // 加载数据
        // loadDataAsyncTask.executeOnExecutor(Executors.newCachedThreadPool());
        if (loadDataAsyncTask != null) {
            loadDataAsyncTask.cancel(true);

        }
        loadDataAsyncTask = new LoadDataAsyncTask();
        loadDataAsyncTask.executeOnExecutor(Executors.newCachedThreadPool());

        include.setVisibility(View.GONE);
        super.onCreateView(inflater, container, savedInstanceState);
        return root;

    }

    @Override
    public void onVisible() {
        if (!hasLoadData) {
            // linearLayout.setBackground(getResources().getDrawable(R.drawable.renwuno));
            // linearLayout.setBackgroundResource(R.drawable.write);
            // new TokenLoadAsyncTask().execute();
        }
    }

    @Override
    public void onTabBottomActivityResult(int requestCode, int resultCode,
                                          Intent data) {
        Log.i("", "-------onTabBottomActivityResult:" + TAG);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5 && requestCode == Activity.RESULT_OK) {
            if (data.hasExtra("type")) {

            }
        }
    }

    /**
     * 加载数据的线程
     */
    class LoadDataAsyncTask extends
            AsyncTask<Void, Integer, Map<String, List<EFRowSet>>> {
        String modelType = model.getType();// 系统名称（类型）
        String requestSearchText = "";

        public LoadDataAsyncTask() {

        }

        public LoadDataAsyncTask(String requestSearchText) {
            this.requestSearchText = requestSearchText;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            LoadingDataUtilBlack.show(getActivity());

        }

        @Override
        protected Map<String, List<EFRowSet>> doInBackground(Void... params) {
            Map<String, List<EFRowSet>> dataMap = new HashMap<String, List<EFRowSet>>();
            try {

                // {id=document_approve, caption=公文审批}
                Map<String, String> document_approveMap = OptionParser
                        .getInstance().getElementById("document_approve");
                // {id=document_approve, caption=合同管理}
                Map<String, String> contract_managerMap = OptionParser
                        .getInstance().getElementById("contract_manager");
                if (document_approveMap != null || contract_managerMap != null) {

                    String token = TokenHelper.getOneToken(modelType, getActivity());
                    if (token != null && !token.equals("")) {
                        Map<String, EFDataSet> netMap = getNetWorkData(token);

                        if (document_approveMap != null && netMap != null) {
                            // XXX 得到合同管理数据
                            if (modelType.equals(CONTRACT)) {
                                EFDataSet flowFileDataSet = netMap
                                        .get(CONTRACT);
                                dataMap = FlowTaskUtil
                                        .openTaskFromEFDataSetToMapNew(
                                                flowFileDataSet, CONTRACT);

                            } else if (!modelType.equals(CONTRACT)
                                    && !modelType.equals("Authorization")
                                    && !modelType.equals("PAGING_PARAM")) {
                                // XXX 得到公文审批数据
                                EFDataSet flowFileDataSet = netMap
                                        .get(modelType);
                                dataMap = FlowTaskUtil
                                        .openTaskFromEFDataSetToMapNew(
                                                flowFileDataSet, modelType);

                            }

                        }

                    } else {
                        return null;
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return dataMap;
        }

        @Override
        protected void onPostExecute(final Map<String, List<EFRowSet>> dataMap) {

            LoadingDataUtilBlack.dismiss();
            mSrl.finishRefresh();
            mSrl.finishLoadMore();
            if (dataMap == null) {
                if (getContext() != null) {
                    ToastUtil.showToast(getContext(), "token获取失败，您可能没有此权限");
                }
            } else if (dataMap.containsKey(model.getType())
                    && dataMap.get(model.getType()).size() > 0) {
                listData.addAll(dataMap.get(model.getType()));
                //  sortByTime(listData);

                //过滤list
                Iterator<EFRowSet> iterator = listData.iterator();
                while (iterator.hasNext()) {
                    EFRowSet rowset = iterator.next();
                    if (rowset.hasKey("count") || rowset.getString("title", "").equals("待办")
                            || rowset.getString("title", "").equals("保留") || rowset.getString("title", "").equals("已办")) {
                        iterator.remove();
                    }
                }
            } else {
                if (getContext() != null) {
                    ToastUtil.showToast(getActivity(), "没有更多数据");
                }
            }
            if (getContext() != null) {
                listViewAdapter.notifyDataSetChanged();
            }

        }

        @Override
        protected void onCancelled() {

            super.onCancelled();
            System.out.println("停止任务");
            mSrl.finishRefresh();
            mSrl.finishLoadMore();
        }

        /**
         * 根据OA的时间排序
         *
         * @param
         */
        private void sortByTime(List<EFRowSet> list) {

            Collections.sort(list, new Comparator<EFRowSet>() {
                public int compare(final EFRowSet msg1, final EFRowSet msg2) {
                    String key = "field3";
                    if ("".equals(msg1.getString("field3", ""))) {
                        key = "field2";
                    }
                    String efTime1 = msg1.getString(key, "");
                    String efTime2 = msg2.getString(key, "");

                    if (efTime1.compareTo(efTime2) == 0) {
                        return 0;
                    } else if (efTime1.compareTo(efTime2) > 0) {
                        return -1;
                    } else {
                        return 1;
                    }
                }

            });
        }

        /**
         * 获取待办已办数据（oa 合同 费用报销）
         * <p>
         * <p>
         * 系统类型名称
         *
         * @param token
         * @return
         */

        private Map<String, EFDataSet> getNetWorkData(String token) {
            // 创建PO
            JParamObject PO = JParamObject.Create();
            JResponseObject RO = null;
            Map<String, EFDataSet> map = null;
            String usereId = AndroidEnvironmentVariable.getUserID();
            String password = AndroidEnvironmentVariable.getPassword();
            Log.i(TAG, "contractNum:" + contractNum);
            Log.i(TAG, "startNum:" + startNum);
            Log.i(TAG, "endNum:" + endNum);

            PO.SetValueByParamName("WB_SYS_KEY", modelType);

            if (CONTRACT.equals(modelType)) {
                PO.SetValueByParamName("CONTRACT_params_tokenIDFromMoblie",
                        token);
                if ("db".equals(typeString)) {// 待办
                    PO.SetValueByParamName("CONTRACT_params_type", "0");
                } else if ("yb".equals(typeString)) {// 已办
                    PO.SetValueByParamName("CONTRACT_params_type", "1");
                }
                // PO.SetValueByParamName("CONTRACT_params_type", "1");
                PO.SetValueByParamName("CONTRACT_params_requestSearch",
                        requestSearchText);
                PO.SetValueByParamName("CONTRACT_params_rowNum",
                        String.valueOf(contractNum));
                PO.SetValueByParamName("CONTRACT_params_pageSize", "10");
                PO.SetValueByParamName("CONTRACT_systemmethod",
                        "GetApprovalListHandler");

            } else if (FFS.equals(modelType)) {// 费用报销
                PO.SetValueByParamName("WB_SYS_KEY", "FFS");
                //  PO.SetValueByParamName(modelType + "_params_startRowNum", "0");
                // PO.SetValueByParamName(modelType + "_params_endRowNum", "10");
                PO.SetValueByParamName("FFS_systemmethod", "GetListHandler");
                PO.SetValueByParamName("FFS_params_tokenIDFromMoblie", token);
                PO.SetValueByParamName("FFS_params_tabId", typeString);
                PO.SetValueByParamName("FFS_params_requestSearch", "");
                PO.SetValueByParamName("FFS_params_RowNum",
                        String.valueOf(gongwenNum));
                //todo 坑死我了 以前这个参数不起作用  后来盈科修改了接口 ，传空字符就无效了
                PO.SetValueByParamName("FFS_params_PageSize", "30");

            } else if (GKOA.equals(modelType)) {//国勘OA
                PO.SetValueByParamName(modelType + "_params_tokenIDFromMoblie",
                        token);
                PO.SetValueByParamName(modelType + "_params_startRowNum", "0");
                PO.SetValueByParamName(modelType + "_params_endRowNum", "10");
                if ("db".equals(typeString)) {// 待办
                    PO.SetValueByParamName(modelType + "_params_type", "0");
                } else if ("yb".equals(typeString)) {// 已办
                    PO.SetValueByParamName(modelType + "_params_type", "1");
                }
                if ("dy".equals(typeString)) {//待阅
                    PO.SetValueByParamName(modelType + "_params_type", "2");
                } else if ("yy".equals(typeString)) {// 已阅
                    PO.SetValueByParamName(modelType + "_params_type", "3");
                }
//                PO.SetValueByParamName(modelType + "_params_requestSearch",
//                        requestSearchText);
                PO.SetValueByParamName(modelType + "_params_query",
                        requestSearchText);
                PO.SetValueByParamName(modelType + "_params_RowNum",
                        String.valueOf(gongwenNum));
                PO.SetValueByParamName(modelType + "_params_PageSize", "10");
                PO.SetValueByParamName(modelType + "_systemmethod",
                        "GetListHandler");

            } else if (GKZBOA.equals(modelType)) {//国勘总部OA
                PO.SetValueByParamName(modelType + "_params_tokenIDFromMoblie",
                        token);
                PO.SetValueByParamName(modelType + "_params_startRowNum", "0");
                PO.SetValueByParamName(modelType + "_params_endRowNum", "10");
                if ("db".equals(typeString)) {// 待办
                    PO.SetValueByParamName(modelType + "_params_type", "0");
                } else if ("yb".equals(typeString)) {// 已办
                    PO.SetValueByParamName(modelType + "_params_type", "1");
                }
                if ("dy".equals(typeString)) {//待阅
                    PO.SetValueByParamName(modelType + "_params_type", "2");
                } else if ("yy".equals(typeString)) {// 已阅
                    PO.SetValueByParamName(modelType + "_params_type", "3");
                }
                PO.SetValueByParamName(modelType + "_params_requestSearch",
                        requestSearchText);
                PO.SetValueByParamName(modelType + "_params_RowNum",
                        String.valueOf(gongwenNum));
                PO.SetValueByParamName(modelType + "_params_PageSize", "10");
                PO.SetValueByParamName(modelType + "_systemmethod", "GetListHandler");

            } else {// OA
                PO.SetValueByParamName(modelType + "_params_tokenIDFromMoblie",
                        token);
                // PO.SetValueByParamName(name + "_params_startRowNum",
                // String.valueOf(startNum));
                // PO.SetValueByParamName(name +
                // "_params_endRowNum",String.valueOf(endNum));
                PO.SetValueByParamName(modelType + "_params_startRowNum", "0");
                PO.SetValueByParamName(modelType + "_params_endRowNum", "10");
                PO.SetValueByParamName(modelType + "_params_type", typeString);
                PO.SetValueByParamName(modelType + "_params_requestSearch",
                        requestSearchText);
                // PO.SetValueByParamName(name + "_params_requestSearch"," ");
                // PO.SetValueByParamName(name + "_params_rowNum", "0");
                PO.SetValueByParamName(modelType + "_params_rowNum",
                        String.valueOf(gongwenNum));
                PO.SetValueByParamName(modelType + "_params_pageSize", "10");
                PO.SetValueByParamName(modelType + "_systemmethod",
                        "GetListHandler");

            }

            try {
                // 连接服务器
                RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (RO != null) {
                System.out.println("map不为空");
                map = RO.getResponseMap();

            }

            CommonPo.setPoToNull();
            return map;
        }
    }

    /**
     * 得到会议申请的数据
     *
     * @return
     */
    @SuppressWarnings("unused")
    private EFDataSet getMeetingApplyData() {
        // 创建PO
        EFDataSet flowTaskDataSet = null;
        JParamObject PO = JParamObject.Create();
        Log.i("Popopoppopop", PO.getEnvValue("DataBaseName", "") + "....");
        // PO.SetValueByParamName("MDL_ID", "HY_HYSQModel");
        // PO.SetValueByParamName("HY_HYSQModel", "MDL_ID");
        PO.SetValueByParamName("QXBZW", "2");
        PO.SetValueByParamName("SELF_SUBMIT_TASK", "1");
        // PO.SetValueByParamName("MDL_UNIT_DCTIDS", "BZZZJGZD");
        PO.SetValueByParamName("MDL_UNIT_DCTIDS", "YHZZJG");
        PO.SetValueByParamName("_CHILD_FLOW_DISP_TYPE_", "1");
        PO.SetValueByParamName("taskDataSetID", "TASKPendingDataSet");
        // PO.SetValueByParamName("TASK_TYPE", "pending");
        try {
            Log.i("xxxxxxxxxxx", EAI.Path);
            flowTaskDataSet = FlowTaskUtil.getFlowTaskData(PO, "pending");
        } catch (Exception e) {
            e.printStackTrace();
        }

        CommonPo.setPoToNull();
        return flowTaskDataSet;
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == 1) {
                if (getActivity() != null) {
                    Toast.makeText(getActivity(), "获取token失败，请检查用户名密码是否正确",
                            Toast.LENGTH_SHORT).show();
                }
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.searchbut) {
            String text = searchEditText.getText().toString();
            if (!text.equals("")) {
                listData.clear();
                startNum = 0;
                endNum = 10;
                contractNum = 1;
                gongwenNum = 0;
                new LoadDataAsyncTask(text).executeOnExecutor(Executors
                        .newCachedThreadPool());
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (loadDataAsyncTask != null) {
            loadDataAsyncTask.onCancelled();
        }
    }
}
